package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: 陈安
 * @Date: 2020/12/11$ 10:04$
 * @Description: 查询
 * @Version 1.0
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public Map search(Map<String, String> searchMap) {
        Map<String, Object> resultMap = new HashMap<>();

        //构建查询
        if (searchMap != null) {
            //构建条件查询封装的对象
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //按照关键字查询
            if (StringUtils.isNotEmpty(searchMap.get("keywords"))) {
                //AND表示是求交集,默认是or是并集
                //matchQuery是进行分词查询(和term不分词正好相对)
                //name表示是我们操作的是哪一个域(其实就是字段),searchMap.get("keywords")表示操作的实际是什么
                boolQuery.must(QueryBuilders.matchQuery("name", searchMap.get("keywords")).operator(Operator.AND));
            }

            //按照品牌进行查询
            if (StringUtils.isNotEmpty(searchMap.get("brand"))) {
                //termQuery表示是不做分词
                //brand是表示操作的是哪一个域(其实就是字段),searchMap.get("brand"))表示操作的是实际是什么.
                boolQuery.filter(QueryBuilders.termQuery("brandName", searchMap.get("brand")));
            }

            //按照规格进行查询
            Set<String> strings = searchMap.keySet();
            for (String string : strings) {
                if (string.startsWith("spec_")) {
                    String value = searchMap.get(string).replace("%2B", "+");
                    boolQuery.filter(QueryBuilders.termQuery(("specMap." + string.substring(5) + ".keyword"), value));
                }
            }

            //按照价格进行区间过滤查询
            if (StringUtils.isNotEmpty(searchMap.get("price"))) {
                String[] prices = searchMap.get("price").split("-");
                if (prices.length == 2) {//这是因为有0-500 和3000的区别的
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            //按照规格进行聚合查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));


            nativeSearchQueryBuilder.withQuery(boolQuery);

            //按照品牌进行分组(分组其实就是聚合,我们平常说的聚合其实就是分组的意思)查询
            //addAggregation()就表示进行聚合,里面放的是聚合也就是分组查询的调条件
            //AggregationBuilder.terms()分组查询过后的列名叫什么
            //filed表示操作的域名
            String skuBrand = "skuBrand";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            //开启分页查询
            String pageNum = searchMap.get("pageNum");  //当前页
            String pageSize = searchMap.get("pageSize");//总页数
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //设置分页
            //第一个参数是当前页,当前页是从0开始的.所以我们需要减一,第二个是每页显示多少条
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));


            //按照相关字段进行排序
            //1:当前域,2:是按照升序还是降序的规则
            if (StringUtils.isNotEmpty(searchMap.get("sortField")) && StringUtils.isNotEmpty(searchMap.get("sortRule"))) {
                if ("ASC".equals(searchMap.get("sortRule"))) {
                    //是升序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.ASC));
                } else {
                    //是降序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((searchMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            //设置高亮域
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")
                    .preTags("<span style='color:red'>")//高亮样式前缀
                    .postTags("</span>");   //高亮样式后缀

            nativeSearchQueryBuilder.withHighlightFields(field);


            //说明有搜索条件,所以就可以开启查询
            //1:条件的构建对象
            //2:查询操作的实体类
            //3"查询结果操作对象
            AggregatedPage<SkuInfo> resultinfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    //查询结果的操作
                    List<T> list = new ArrayList<>();

                    //获取查询结果命中的数据
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            //将他转化为skuinfo
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);

                            //将没有高亮的替换为高亮的
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                //替换数据
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }


                            //存入list中
                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //封装最终的返回结果
            //总记录数
            long totalElements = resultinfo.getTotalElements();
            resultMap.put("total", totalElements);

            //总分页数
            int totalPages = resultinfo.getTotalPages();
            resultMap.put("totalPage", totalPages);

            //数据集合
            List<SkuInfo> content = resultinfo.getContent();
            resultMap.put("rows", content);

            //封装品牌的分组计结果,表示对skubrand进行分组
            StringTerms brandTerms = (StringTerms) resultinfo.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);

            //封装规格分组结果
            StringTerms specTerms = (StringTerms) resultinfo.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", specList);

            //封装当前页
            resultMap.put("pageNum", pageNum);

            return resultMap;

        }

        //封装查询结果

        return null;
    }
}
